package com.tianxin.workbao.workBao.dataProvide;

import android.content.Context;

import com.alibaba.fastjson.JSON;
import com.tianxin.workbao.workBao.R;
import com.tianxin.workbao.workBao.bean.OutputBillDao;
import com.tianxin.workbao.workBao.bean.Totalstatic;
import com.tianxin.workbao.workBao.bean.TotalstaticDao;
import com.tianxin.workbao.workBao.common.Constant;
import com.tianxin.workbao.workBao.common.URL;
import com.tianxin.workbao.workBao.listener.UpdateListViewListener;
import com.tianxin.workbao.workBao.okhttp.CommonOkHttpClient;
import com.tianxin.workbao.workBao.okhttp.exception.OkHttpException;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataHandle;
import com.tianxin.workbao.workBao.okhttp.listener.DisposeDataListener;
import com.tianxin.workbao.workBao.okhttp.request.CommonRequest;
import com.tianxin.workbao.workBao.okhttp.request.RequestParams;
import com.tianxin.workbao.workBao.utils.common.NetworkUtils;
import com.tianxin.workbao.workBao.utils.common.UIUtils;

import org.greenrobot.greendao.query.Query;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by hacker on 2017/7/25.
 */

public class TotalStaticProvide extends BaseDataProvide {


    private Totalstatic mTotalstatic;
    private UpdateListViewListener mUpdateListViewListener;
    private TotalstaticDao totalstaticDao;

    public TotalStaticProvide(Context context, UpdateListViewListener listener) {
        super(context);
        mUpdateListViewListener = listener;
        totalstaticDao = mGreenDaoHelper.getDaoSession().getTotalstaticDao();
    }


    @Override
    public DisposeDataHandle getDisposeDataHandle() {
        disposeDataHandle = new DisposeDataHandle(getDisposeDataListener());
        return disposeDataHandle;
    }

    @Override
    public DisposeDataListener getDisposeDataListener() {
        disposeDataListener = new DisposeDataListener() {
            @Override
            public void onSuccess(Object responseObj) {
                mUpdateListViewListener.hideProgress();
                try {
                    JSONObject object = new JSONObject(responseObj.toString());
                    int status = object.getInt(Constant.RESPONSE_STATUS);
                    String information = object.getString(Constant.RESPONSE_INFO);
                    if (status > 0) {
                        String dataJson = object.getString(Constant.RESPONSE_DATA);
                        if (dataJson != null || dataJson.length() > 2) {
                            try {
                                mTotalstatic = JSON.parseObject(dataJson, Totalstatic.class);
                                refreshUI();
                                saveToDb(mTotalstatic);
                            } catch (Exception e) {
                                mUpdateListViewListener.showMessage("total statistic To Bean Error :类型转换出错" + e.getMessage());
                            }
                        } else {
                            mUpdateListViewListener.showMessage(information);
                        }
                    } else {

                        mUpdateListViewListener.showMessage(information);
                    }
                } catch (JSONException e) {
                    showRequestErrorMessage(mUpdateListViewListener, responseObj.toString());
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(Object reasonObj) {
                mUpdateListViewListener.hideProgress();
                if (reasonObj instanceof OkHttpException) {
                    OkHttpException exception = (OkHttpException) reasonObj;
                    mUpdateListViewListener.showMessage(exception.getEcode() + ":" + exception.getEmsg().toString());
                } else {
                    showRequestErrorMessage(mUpdateListViewListener, reasonObj.toString());
                }
            }
        };
        return disposeDataListener;
    }

    /**
     * true save data to databases
     *
     * @param obj
     */
    private void saveToDb(Object obj) {
        totalstaticDao.insertOrReplace((Totalstatic) obj);
    }

    /**
     * update the output bill  data  from server
     */
    private void getFromServer() {
        mUpdateListViewListener.showProgress();
        Map<String, String> map = new HashMap<>();
        map.put(Constant.APPTOKEN_NAME, getAppToken());
        RequestParams params = new RequestParams(map);
        CommonOkHttpClient.post(CommonRequest.createPostRequest(
                URL.getTotalStatisticUrl(), params), getDisposeDataHandle());

    }

    public void getdatas() {
        if (!NetworkUtils.isConnected(UIUtils.getContext())) {
            mUpdateListViewListener.hideProgress();
            mUpdateListViewListener.showMessage(mContext.getResources().getString(R.string.poor_network));
            getFromDb();
        } else {
            getFromServer();
        }
    }

    private void getFromDb() {
        Query<Totalstatic> query = totalstaticDao.queryBuilder()
                .where(OutputBillDao.Properties.Isis.eq(1))
                .orderDesc(TotalstaticDao.Properties.Id)
                .limit(1)
                .build();
        List<Totalstatic> list = query.list();
        if (list.size() > 0) {
            mTotalstatic = list.get(0);
        }
        refreshUI();
    }

    @Override
    public void refreshUI() {
        mUpdateListViewListener.onRefreshData(mTotalstatic);
    }


}
